import { ScrollView, View, Text, Image, Button } from '@tarojs/components';
import React, { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { AtModal, AtModalHeader, AtModalContent, AtModalAction } from 'taro-ui';
import { connect } from 'react-redux';
import './index.less';
import * as T from './types';
import actions from './actions';
import { store2Props } from './selectors';
import Blank from '@/pages/common/blank';
import 'taro-ui/dist/style/components/modal.scss';
import * as sdk from 'api/fetch';
import config from '@/service/config';
import moment from 'dayjs';
import api from 'api';
import bgImg from '@/assets/image/openDoor/o_bg.png';
import bg1Img from '@/assets/image/openDoor/o_bg1.png';
import bg2Img from '@/assets/image/openDoor/o_bg2.png';
import topImg from '@/assets/image/openDoor/l_top.png';
import topaImg from '@/assets/image/openDoor/l_top_a.png';
import centerImg from '@/assets/image/openDoor/l_center.png';
import centeraImg from '@/assets/image/openDoor/l_center_a.png';
import bottomImg from '@/assets/image/openDoor/l_bottom.png';
import bottomaImg from '@/assets/image/openDoor/l_bottom_a.png';
import messageImg from '@/assets/image/none/message-comment.png';
import rightImg from '@/assets/image/openDoor/i_right.png';
import mainImg from '@/assets/image/openDoor/main.png';
import icon1Img from '@/assets/image/openDoor/icon1.png';
import icon2Img from '@/assets/image/openDoor/icon2.png';
import icon3Img from '@/assets/image/openDoor/icon3.png';
import icon4Img from '@/assets/image/openDoor/icon4.png';
import BlacklistModel from '@/pages/common/blacklist-model';

actions().actions.loadReducer();
// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class Index extends Component<Partial<T.IProps>, any> {
  constructor(props) {
    super(props);
    this.state = {
      bigDoor: true,
      cell: false,
      serve: false,
      isOpenDoor: false,
      current: 0,
      userInfo: {
        communityName: '',
      },
      modalVisible: false,
      AgreementVisible: false,
      RequireVisible: false,
      imgClick: true,
      isShow: false,
      doorName: '',
      detail: {},
    };
  }

  componentDidMount() { }

  componentDidShow() {
    let {
      main: { },
      actions: { action },
    } = this.props;

    const title = Taro.getStorageSync("taskModel");
    if (title) {
      Taro.showToast({
        title,
        icon: 'none',
      });
      Taro.removeStorageSync("taskModel");
    }



    let itemStr = Taro.getStorageSync('b2b-wechat@login');
    let selectDistance = Taro.getStorageSync('selectDistance');
    if (itemStr) {
      let userInfo = itemStr.user;
      action.commonChange([
        {
          paths: 'main.selectDistance',
          value: selectDistance,
        },
        {
          paths: 'main.userInfo',
          value: userInfo,
        },
      ]);
      if (userInfo.status == 3) {
        //物业审核通过
        this.props.actions.init();
      } else {
        this.initjudge();
        this.setState({
          doorName: '',
          detail: {},
        });
        action.commonChange([
          {
            paths: 'main.doorList',
            value: [],
          },
          {
            paths: 'main.unitDoorList',
            value: [],
          },
        ]);
      }
    }
  }

  componentWillUnmount() {
    this.props.actions.clean();
  }

  async onShareAppMessage() {
    //触发分享，任务完成
    let task = Taro.getStorageSync('task');
    if (task) {
      task = JSON.parse(task)
      let id = task.id;
      const result = await api.TaskCenterController.completedTask({ id })
      // setTimeout(()=>{
      // Taro.showToast({
      //               title: `获得${task.taskInfoVO.rewardType == 0 ? task.taskInfoVO.rewardPoints : ""}${["积分", "优惠券", "实物商品"][task.taskInfoVO.rewardType]}${task.taskInfoVO.rewardType == 2 ? "请到我的-我的奖励中填写收货地址":""}`,
      //               icon: 'none',
      //             });
      Taro.removeStorageSync("task");
      Taro.setStorageSync("taskModel", `获得${task.taskInfoVO.rewardType == 0 ? task.taskInfoVO.rewardPoints : ""}${["积分", "优惠券", "实物商品"][task.taskInfoVO.rewardType]}${task.taskInfoVO.rewardType == 2 ? "请到我的-我的奖励中填写收货地址" : ""}`)
      // },5000)
    }
    let wechatShareInfo = JSON.parse(Taro.getStorageSync('wechatShareInfo'));
    return {
      title: wechatShareInfo.title,
      imageUrl: wechatShareInfo.imgUrl[0].url,
    };
  }

  async changeMenu(data) {
    let {
      actions: { action },
    } = this.props;
    let itemStr = Taro.getStorageSync('b2b-wechat@login');
    if (!itemStr) {
      Taro.navigateTo({
        url: '/pages/package-C/login/login/index',
      });
      return;
    } else {
      if (Taro.getStorageSync('blacklistModel')) {
        action.commonChange('main.blacklistModel', true);
        return;
      }
      let userInfo = itemStr.user;
      if (userInfo.status == 3) {
        this.setState({
          isOpenDoor: false,
          doorName: '',
          detail: {},
        });
        switch (data) {
          case 0:
            this.setState({ bigDoor: true, cell: false, serve: false });
            break;
          case 1:
            this.setState({ bigDoor: false, cell: true, serve: false });
            break;
          case 2:
            this.setState({ bigDoor: false, cell: false, serve: true });
            break;
          default:
            break;
        }
      } else {
        this.initjudge();
      }
    }
  }

  renderDoorList(list) {
    let { isOpenDoor, bigDoor, detail } = this.state;
    let listView = [];
    list.map((item, index) => {
      listView.push(
        <View className="item" onClick={() => this.chooseDoor(item)}>
          <View style={{ flex: 1 }}>
            <Text className="i_text">{item.communityName + ' ' + item.name}</Text>
          </View>
          <View className="statusBox">
            {bigDoor && item.deviceId == detail.deviceId && isOpenDoor ? (
              <Text className="statusText_a">已开门</Text>
            ) : (
              <Text className="statusText">未开门</Text>
            )}
          </View>
        </View>,
      );
    });
    return listView;
  }

  renderUnitList(list) {
    let { isOpenDoor, cell, detail } = this.state;
    let listView = [];
    list.map((item, index) => {
      listView.push(
        <View className="item" onClick={() => this.chooseDoor(item)}>
          <View style={{ flex: 1 }}>
            <Text className="i_text">
              {item.communityName + ' ' + item.buildingName + '栋' + item.unitName + '单元'}{' '}
              {item.position == 1 ? '地上' : item.position == 2 ? '地下左' : '地下右'}
            </Text>
          </View>
          <View className="statusBox">
            {cell && item.thirdPartyUnitId == detail.thirdPartyUnitId && isOpenDoor ? (
              <Text className="statusText_a">已开门</Text>
            ) : (
              <Text className="statusText">未开门</Text>
            )}
          </View>
        </View>,
      );
    });
    return listView;
  }

  //选择是哪个门
  chooseDoor(item) {
    let {
      actions: { action },
    } = this.props;
    let { bigDoor, cell } = this.state;
    if (Taro.getStorageSync('blacklistModel')) {
      action.commonChange('main.blacklistModel', true);
      return;
    }
    let doorName = '';
    if (bigDoor) {
      //大门
      doorName = item.communityName + ' ' + item.name;
    } else if (cell) {
      let position = item.position == 1 ? '地上' : item.position == 2 ? '地下左' : '地下右';
      //单元门
      doorName = item.communityName + ' ' + item.buildingName + '栋' + item.unitName + '单元' + position;
    }
    this.setState({ doorName, detail: item }, () => {
      this.openLockClick();
    });
  }

  async openLockClick() {
    let { isOpenDoor, bigDoor, cell, detail, doorName } = this.state;
    if (doorName == '') {
      Taro.showToast({
        title: '请先选择需要开锁的门！',
        icon: 'none',
        duration: 2000,
      });
      return;
    }
    Taro.showLoading({
      title: '开门中...',
    });
    this.setState({ showLoading: true }, () => {
      if (!isOpenDoor && bigDoor && detail.deviceId) {
        //开大门
        this.openDoorById(detail.deviceId);
      } else if (!isOpenDoor && cell && detail.thirdPartyUnitId) {
        //开单元门
        this.openDoorById(detail.thirdPartyUnitId);
      }
    });
  }

  //点击开门
  async openDoorById(equipmentId) {
    let {
      main: { userInfo },
      actions: { action },
    } = this.props;
    let params = {
      equipmentId,
      communityId: userInfo.communityId,
    };
    this.setState({ isOpenDoor: true, showLoading: true });
    let res = await api.openDoorController.openDoorById(params);
    if (res.success) {
      Taro.hideLoading();
      this.setState({ isOpenDoor: true, showLoading: false }, () => {
        Taro.showToast({
          title: '开门成功！',
          icon: 'none',
          duration: 2000,
        });
      });
      setTimeout(() => {
        this.setState({
          isOpenDoor: false,
        });
      }, 3000);
    } else {
      Taro.hideLoading();
      this.setState({ doorName: '', detail: {}, isOpenDoor: false, showLoading: false }, () => {
        Taro.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000,
        });
      });
    }
  }

  async onImageClick(e) {
    let that = this;
    Taro.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
      success: async function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;

        /// 图片压缩
        const tmpFiles: any = await that.compressfiles(res.tempFiles);

        /// 将选中的图片存在files中
        var tmpFileList = tmpFiles.map((file) => {
          return {
            url: file.path,
          };
        });

        /// 发起网络请求 将tag有值的数据进行上传 如果上传成功则移除tag值
        // 获取上传Token
        let { data } = await sdk.rzget('oss/sign', {});
        let avatarUrl = tmpFileList[0].url;
        Taro.uploadFile({
          url: config.ossHost,
          filePath: avatarUrl,
          name: 'file', // 必须填file。
          formData: {
            OSSAccessKeyId: data.accessid,
            policy: data.policy,
            signature: data.signature,
            key: `itsource/${avatarUrl.slice(avatarUrl.length / 2)}`,
            // 'x-oss-security-token': securityToken // 使用STS签名时必传。
          },
          success: (res) => {
            if (res.statusCode === 204) {
              avatarUrl = `${config.ossHost}/itsource/${avatarUrl.slice(avatarUrl.length / 2)}`;
              // API
              that.props.actions.action.uploadUserPicture(avatarUrl);
            }
          },
          fail: (err) => {
            console.log(err);
            Taro.showToast({
              title: '上传失败！',
              icon: 'none',
              mask: true,
            });
            /// 上传失败
          },
        });
      },
    });
  }

  /// 图片压缩
  compressfiles = async (uploadFiles = []) => {
    let that = this;
    let files = [];
    const count = uploadFiles?.length || 0;
    Taro.showLoading({
      title: '压缩中...',
    });

    return new Promise(async (resolve, reject) => {
      for (let index = 0; index < count; index++) {
        const file = uploadFiles[index];
        const res = await this.compressfile(file);
        console.log(index);
        files.push(res);
        if (index === count - 1) {
          Taro.hideLoading();
          resolve(files);
        }
      }
    });
  };

  /// 单个图片压缩
  compressfile = async (file) => {
    let that = this;
    return new Promise((resolve, reject) => {
      /// 压缩图片  图片小于300k直接上传 如果大于300k则压缩图片大小
      const maxSize = 300 * 1024;
      const fileSize = file.size;
      if (fileSize > maxSize) {
        Taro.getImageInfo({
          src: file.path,
          success: async (data) => {
            //---------利用canvas压缩图片--------------
            var canvasWidth = data.width; //图片原始长宽
            var canvasHeight = data.height;
            // if (canvasWidth > 500) {
            //   canvasWidth = 500;
            //   canvasHeight = canvasHeight / (data.width / 500);
            // }
            let interval = 500;
            /// 时间处理 根据图片大小 在导出图片时延时一定时间后开始处理返回数据，防止数据未导出成功
            const kb = fileSize / 1000;
            if (kb < 1000) {
              interval = 500;
            } else {
              interval = kb / 20;
            }

            //----------绘制图形并取出图片路径--------------
            var ctx = Taro.createCanvasContext('myCanvas');
            ctx.drawImage(file.path, 0, 0, canvasWidth, canvasHeight);
            ctx.draw(
              false,
              // @ts-ignore
              setTimeout(() => {
                Taro.canvasToTempFilePath({
                  canvasId: 'myCanvas',
                  destWidth: canvasWidth,
                  destHeight: canvasHeight,
                  success: async function (data1) {
                    console.log(data1.tempFilePath, '<<<<<<SUCCESS');
                    resolve({
                      path: data1.tempFilePath,
                    });
                  },
                  fail: function (data1: any) {
                    // 压缩失败时上传基础缓存
                    console.log('压缩失败时上传基础缓存');
                    resolve({
                      path: file.path,
                    });
                  },
                });
              }, interval),
            );
          },
        });
      } else {
        resolve(file);
      }
    });
  };

  // status：0待审核、1业主审核通过、2业主审核不通过、3物业审核通过、4物业审核不通过'
  async initjudge() {
    let itemStr = Taro.getStorageSync('b2b-wechat@login');
    if (itemStr) {
      let userInfo = itemStr.user;
      if (userInfo.communityName) {
        switch (userInfo.status) {
          case 0:
            await Taro.showToast({
              title: '绑定房屋正在审核中',
              icon: 'none',
              duration: 2000,
            });
            break;
          case 1:
            await Taro.showToast({
              title: '绑定房屋正在审核中',
              icon: 'none',
              duration: 2000,
            });
            break;
          case 2:
            await Taro.showToast({
              title: '绑定房屋未通过审核，请联系业主',
              icon: 'none',
              duration: 2000,
            });
            break;
          case 3:
            this.setState({
              isShow: false,
            });
            break;
          case 4:
            await Taro.showToast({
              title: '绑定房屋未通过审核，请联系业主',
              icon: 'none',
              duration: 2000,
            });
            break;
          default:
            this.setState({
              isShow: true,
            });
            break;
        }
      } else {
        this.setState({
          isShow: true,
        });
      }
    }
  }

  render() {
    let {
      main: { doorList, unitDoorList, selectDistance, userInfo, facePictureUrl, blacklistModel },
      actions: { action },
    } = this.props;
    let { bigDoor, cell, serve, isShow } = this.state;
    return (
      <View className="packageOpenDoor">
        <Image className="bgImg" src={bigDoor ? bg1Img : cell ? bgImg : serve ? bg2Img : bg1Img} mode="widthFix" />
        <View className="t_box">
          <Text className="t_title">欢迎回家</Text>
          <Text className="t_name">{selectDistance.name ? selectDistance.name : ''}</Text>
        </View>
        <View className="b_box">
          <View className="b_left">
            <View className="l_tab_box" onClick={() => this.changeMenu(0)}>
              <View className="l_img_box">
                {bigDoor ? (
                  <Image className="t_icon" mode="widthFix" src={topaImg} />
                ) : (
                  <Image className="t_icon" mode="widthFix" src={topImg} />
                )}
              </View>
              <Text className="t_font" style={{ color: `${bigDoor ? '#218CFF' : '#999999'}` }}>
                小区大门
              </Text>
            </View>
            <View className="l_tab_box" onClick={() => this.changeMenu(1)}>
              <View className="l_img_box">
                {cell ? (
                  <Image className="t_icon" mode="widthFix" src={centeraImg} />
                ) : (
                  <Image className="t_icon" mode="widthFix" src={centerImg} />
                )}
              </View>
              <Text className="t_font" style={{ color: `${cell ? '#218CFF' : '#999999'}` }}>
                单元门
              </Text>
            </View>
            <View className="l_tab_box" onClick={() => this.changeMenu(2)}>
              <View className="l_img_box">
                {serve ? (
                  <Image className="t_icon" mode="widthFix" src={bottomaImg} />
                ) : (
                  <Image className="t_icon" mode="widthFix" src={bottomImg} />
                )}
              </View>
              <Text className="t_font" style={{ color: `${serve ? '#218CFF' : '#999999'}` }}>
                人脸识别
              </Text>
            </View>
          </View>
          <View className="b_right">
            <ScrollView scrollY className="scrollView">
              {bigDoor && doorList.length > 0 && this.renderDoorList(doorList)}
              {cell && unitDoorList.length > 0 && this.renderUnitList(unitDoorList)}
              {bigDoor && doorList.length == 0 && (
                <Blank
                  content="还未配置大门设备～"
                  img={messageImg}
                  imgStyle={{ width: '400rpx', height: '400rpx' }}
                  textStyle={{
                    fontSize: '32rpx',
                    color: '#999999',
                    textAlign: 'center',
                    marginTop: '40rpx',
                  }}
                />
              )}
              {cell && unitDoorList.length == 0 && (
                <Blank
                  content="还未配置单元门设备～"
                  img={messageImg}
                  imgStyle={{ width: '400rpx', height: '400rpx' }}
                  textStyle={{
                    fontSize: '32rpx',
                    color: '#999999',
                    textAlign: 'center',
                    marginTop: '40rpx',
                  }}
                />
              )}
              {serve && (
                <View style={{ flex: 1 }}>
                  <View className="r_sb">
                    <View style={{ flexDirection: 'row', justifyContent: 'center' }}>
                      <Image className="pictureUrl" src={userInfo.pictureUrl} mode="aspectFill"></Image>
                      <Text className="name">{userInfo.name}</Text>
                    </View>
                    <View
                      onClick={() => {
                        Taro.navigateTo({
                          url: '/pages/package-C/door-setting/index',
                        });
                      }}
                    >
                      <Image className="right" src={rightImg} mode="widthFix"></Image>
                    </View>
                  </View>
                  <View className="facePicBox">
                    <View onClick={this.onImageClick.bind(this)}>
                      {facePictureUrl ? (
                        <Image className="facePic" mode="widthFix" src={facePictureUrl} />
                      ) : (
                        <Image className="facePic" mode="widthFix" src={mainImg} />
                      )}
                    </View>
                  </View>
                  <View>
                    <Text className="icon_title">照片要求</Text>
                    <View style={{ flexDirection: 'row' }}>
                      <View className="f_item">
                        <View className="center">
                          <Image className="f_icon" src={icon1Img} mode="widthFix" />
                        </View>
                        <Text className="f_text">标准拍摄</Text>
                      </View>
                      <View className="f_item">
                        <View className="center">
                          <Image className="f_icon" src={icon2Img} mode="widthFix" />
                        </View>
                        <Text className="f_text">遮挡脸部</Text>
                      </View>
                      <View className="f_item">
                        <View className="center">
                          <Image className="f_icon" src={icon3Img} mode="widthFix" />
                        </View>
                        <Text className="f_text">拍摄不全</Text>
                      </View>
                      <View className="f_item">
                        <View className="center">
                          <Image className="f_icon" src={icon4Img} mode="widthFix" />
                        </View>
                        <Text className="f_text">光线不足</Text>
                      </View>
                    </View>
                  </View>
                </View>
              )}
            </ScrollView>
          </View>
        </View>
        {isShow && (
          <AtModal
            isOpened={isShow}
            title="温馨提示"
            cancelText="取消"
            confirmText="去绑定"
            onClose={() => {
              this.setState({
                isShow: false,
              });
            }}
            onCancel={() => {
              this.setState({
                isShow: false,
              });
            }}
            onConfirm={() => {
              this.setState(
                {
                  isShow: false,
                },
                () => {
                  Taro.navigateTo({
                    url: '/pages/package-A/house/add/index',
                  });
                },
              );
            }}
            content="绑定房屋后才能使用此功能，请先去绑定哦～"
          />
        )}
        <BlacklistModel
          isOpened={blacklistModel}
          onConfirm={() => {
            action.commonChange('main.blacklistModel', false);
          }}
          onCancel={() => {
            action.commonChange('main.blacklistModel', false);
          }}
        />
      </View>
    );
  }
}
